import cv2
import queue
import threading
import numpy as np
# 输入你的摄像头 RTSP 或 HTTP 地址
url = "http://10.193.190.99:4747/video"


class VideoCapture:

    def __init__(self, name):
        self.cap = cv2.VideoCapture(name)

        self.cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 380)
        ret = self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 380)
        print(ret)
        self.cap.set(cv2.CAP_PROP_FPS, 30)



        self.q = queue.Queue()
        t = threading.Thread(target=self._reader)
        t.daemon = True
        t.start()

    # 帧可用时立即读取帧，只保留最新的帧
    def _reader(self):
        while True:
            ret, frame = self.cap.read()
            if not ret:
                break
            if not self.q.empty():
                try:
                    self.q.get_nowait()   # 删除上一个（未处理的）帧
                except queue.Empty:
                    pass
            self.q.put(frame)

    def read(self):
        return self.q.get()

# if __name__ == '__main__'
#     cap = VideoCapture(url)
#     while True:
#         # 读取每一帧
#         frame = cap.read()
#         h, w, _ = frame.shape

#         scale = 384.0 / max(h, w)
#         new_w = int(w * scale)
#         new_h = int(h * scale)

#         resized_frame = cv2.resize(frame, (new_w, new_h))
#         result_frame = np.zeros((384, 384, 3), dtype=np.uint8)
#         x_offset = (384 - new_w) // 2
#         y_offset = (384 - new_h) // 2
#         result_frame[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_frame


#         cv2.imshow("img", result_frame)
#         cv2.waitKey(1)

